import ChatManager from '../component/ChatManager';
import Api from '../service/Api';

// 计数形的系统消息ids
export const num_events = [
  '9408',
  '9402',
  '9414',
  '9701',
  '9412',
  '2201'
]

const ICONS = {
  "2305": "img/news_public/sys_msg_loading.png",  // 通知进度提醒
  "2306": "img/news_public/sys_status_change.png", // 通知状态变更提醒
  "9406": "img/news_public/out_cancel.png", // 外出撤回
  "9407": "img/news_public/out_reject.png", // 外出拒绝
  "9409": "img/news_public/out_wating.png", // 外出待审核
  "9411": "img/news_public/out_ok.png", // 外出通过
  "9412": "img/news_public/confirm_event.png", // 确认事务
  "9413": "img/news_public/event_msg.png", // 事务信息
  "9414": "img/news_public/accept_event.png", // 接受事务
  "9402": "img/news_public/dianpin.png", // 点评
  "9408": "img/news_public/foot_circle.png", // 足迹圈
  "default": "img/news_public/sys_msg.png" // 默认通知
}


export function news_sys_page() {
  console.log(`---------------------sys`);
  let dataArr = ChatManager.getAllSysMessage();
  let AllNotRead = 0; // 总未读数目

  dataArr.sort(function(a, b) {
    if (a.ts > b.ts) { // 新消息排在前面
      return -1;
    }
    if (a.ts < b.ts) {
      return 1;
    }
    return 0;
  })

  console.log(dataArr)
  console.log(55555555555555555)
  if (dataArr.length < 1) {
    window.nonePage();
    return ;
  }

  window.chatWinId = 0; // 设置当前窗口为0代表系统页

  const {User_ID, SessionID, Unit_ID } = JSON.parse(localStorage.getItem('yxtUser'));

  const tpl = `
    <div class="top">
      <p>系统消息</p>
      <a class="read">一键已读</a>
    </div>
    <div class="news_num">
      <ul>
        ${dataArr.map(item => {
          const message = item.message;
          const notRead = item.messages.reduce((acc, curr) => {
            if (curr.IsRead != '2') {
              return acc + 1;
            } else {
              return acc;
            }
          }, 0);
          const isCalType = num_events.indexOf(item.id) > -1; // 判断是否是计数型
          console.log(item.message.IsShow)
          AllNotRead += isCalType ? 0 : notRead;
          if(item.message.IsShow==1){
          return `
            <li><a class="li_btn" data-id="${item.id}" >
              <img src="${ICONS[item.id] ? ICONS[item.id] : ICONS['default']}"/>
              <p class="tit">${message.SendName}<span>${moment(message.SendDate, 'YYYY/M/D H:mm:ss').format('YYYY-MM-DD mm:ss')}</span></p>
              <p class="main">${message.MsgContent ? message.MsgContent : '无最新消息'}。 （点击查看详情）</p>
              ${
                !isCalType && notRead && message.IsShow != '0' ? `<span class="num">${notRead}</span>` : ``
              }
            </a></li>
          `}
        }).join('')}
      </ul>
    </div>
  `;

  $('.right').html(tpl);

  $('a.read').click(function() {
    // alert(`一键已读`);
    if(!AllNotRead){
      return ;
    }

    // 设为已读
    layer.msg('稍等一会儿~', {time: 0});
    Api.get(`/BasePlate/Interface/IInterfaceJson.asmx/RemindMessage_ReadAll`, {
      User_ID, SessionID, Unit_ID
    }).then(resp => {
      if (resp.Goodo.EID == '0') {
        layer.msg('设置已读成功', {time: 1000}, () => news_sys_page());
      } else {
        layer.msg(`设置已读失败：${resp.Goodo.ErrorMessage}`, {time: 1000});
      }
    });
  });

  $('.li_btn').click(function(event){
    const id = `${$(this).data('id')}`;
    if (num_events.indexOf(id) > -1) { // 为计数型消息 --- 需要跳转到相应业务页面
      alert(`请登录手机端或者后台进行查看1`)
    } else { // 单条型 --- 渲染列表
      alert(`请登录手机端或者后台进行查看2`)
    }
//   const id = `${$(this).data('id')}`;
//  if (num_events.indexOf(id) > -1) { // 为计数型消息 --- 需要跳转到相应业务页面
//    alert(`跳转相应业务页面：${id}`)
//  } else { // 单条型 --- 渲染列表
//    render_lv2_sys(id)
//  }
//		console.log(event)
//		console.log(111111111111111111)
////		event.stopPropagation();
//$('.li_btn').css('user-select','none');;
//		alert('请登录手机端或者后台进行查看');
//
//		console.log(22222222222222222)
  })

}

function render_lv2_sys(id) {
  console.log(`---------------------sys2`);
  const dataArr = ChatManager.getSysMessage(id);
  console.log(dataArr);
  if (!dataArr.messages || dataArr.messages.length < 1) {
    return ;
  }

  const {User_ID, SessionID, Unit_ID } = JSON.parse(localStorage.getItem('yxtUser'));

  const tpl = `
    <div class="top">
      <p>系统消息</p>
      <a class="back_btn"><img src="img/news_public/news_sys.png"/></a>
      <a class="read">一键已读</a>
    </div>
    <div class="news_alone">
      <ul>
        ${dataArr.messages.map(item => {
          return `
            <li>
              <p class="time">${moment(item.SendDate, 'YYYY/M/D H:mm:ss').format('MM-DD HH:mm')}</p>
              <div class="${item.IsRead == '2' ? 'disable' : ''}">
                <p class="main ${item.IsRead == '2' ? 'readed' : ''}" data-id="${item.Message_ID}">${item.MsgContent ? item.MsgContent : ' 消息为空'}<span class='read_btn'>已读</span></p>
                <a data-id="${item.Message_ID}" class='detail_btn'>点击查看详情</a>
              </div>
            </li>
          `
        }).join('')}
      </ul>
      <p class="prompt">已加载完</p>
    </div>
  `

  $('.right').html(tpl);
  $('a.detail_btn').click(function(){
    alert(`messageId: ${$(this).data('id')}`)
  })

  // 单个已读事件
  $('div.news_alone').on('click', 'span.read_btn', function() {
    const dom = $(this).parent();
    if (dom.hasClass('readed')) return;

    // 将单条设为已读的接口
    layer.msg('稍等一会儿~', {time: 0});
    Api.get(`/BasePlate/Interface/IInterfaceJson.asmx/Message_ReadMulti`, {
      User_ID, SessionID, MessageIDs: dom.data('id'), IsRead: 2, Unit_ID
    }).then(resp => {
      if (resp.Goodo.EID == '0') {
        layer.msg('设置已读成功', {time: 1000});
        dom.addClass('readed');
        dom.parent().addClass('disable');
      } else {
        layer.msg(`设置已读失败：${resp.Goodo.ErrorMessage}`, {time: 1000});
      }
    });

  });

  // 一键已读事件
  $('a.read').click(function() {
    // alert(`一键已读`);
    const notReads = $('.news_alone p.main:not(.readed)');
    if (notReads.length < 1) {
      return ;
    }
    let ids = []; // 未读的ids
    // 获取ids;
    notReads.each(function() {
      ids.push($(this).data('id'))
    });
    // 设为已读
    layer.msg('稍等一会儿~', {time: 0});
    Api.get(`/BasePlate/Interface/IInterfaceJson.asmx/Message_ReadMulti`, {
      User_ID, SessionID, MessageIDs: ids.join(','), IsRead: 2, Unit_ID
    }).then(resp => {
      if (resp.Goodo.EID == '0') {
        layer.msg('设置已读成功', {time: 1000});
        notReads.each(function() {
          $(this).addClass('readed')
          $(this).parent().addClass('disable');
        })
      } else {
        layer.msg(`设置已读失败：${resp.Goodo.ErrorMessage}`, {time: 1000});
      }
    });
  });

  $('a.back_btn').click(function() {
    news_sys_page();
  })

}
